var api = "/api/";
var login, userstatus, register, ranks, title, openSubpage, currentState, k;

if(typeof Clientcide != 'undefined')
Clientcide.setAssetLocation('http://static.rshun.hu/depender/libs/clientcide/Assets');

Locale.use('hu-HU');

Element.implement({
	addSpinner: function(){
		return new Element('span', {'class' : 'spinner spinspan'}).inject(this);
	},
	removeSpinner: function(){
		(function(){this.getChildren('.spinner').dispose();}).delay(500, this);
	},
	clearForm: function(){	
		this.getElements('input[type=text]').set('value', '');
		this.getElements('input[type=password]').set('value', '');
		this.getElements('textarea').set('text', '');
	}
});

var ScScroller = new Class({
    Implements: [Options],
    options: {
			hideWhenNoOverflow: true,
			onScroll: function(){}
    },
    timeslider: $empty(),
		element: $empty(),
		handler: $empty(),
		scrollarea: $empty(),
		hidden: true,
    initialize: function(element, options) {
			this.element = element;		
			this.setOptions(options);
			var scrollbars = function(){

				scrollarea = new Element('div', {'class' : 'scrollarea'});
				new Element('div', {'class' : 'scrTop'}).inject(scrollarea);
				new Element('div', {'class' : 'scrCenter'}).inject(scrollarea);
				new Element('div', {'class' : 'scrBottom'}).inject(scrollarea);
				cont = new Element('div', {'class' : 'scrollBarContainer'}).inject(scrollarea);
				handler = new Element('div', {'class' : 'scrollKnob'}).inject(cont);
				new Element('div', {'class' : 'hTop'}).inject(handler);
				new Element('div', {'class' : 'hCenter'}).inject(handler);
				new Element('div', {'class' : 'hBottom'}).inject(handler);
				
				scrollarea.inject(element, 'before');
				
				this.scrollarea = scrollarea;
				this.handler = handler;
			}.bind(this);
			
			this.element.update = this.update.bind(this);	
			
			scrollbars();
			
			el = this.element;
			hand = this.handler;

			this.element.addEvent('scroll', this.options.onScroll);

			this.timeslider = new MooScroller(el, hand, {
			    hideWhenNoOverflow: this.options.hideWhenNoOverflow
			});
			
			this.update();
    },

    update: function() {
			var el = this.element;
			var hand = this.handler;
			var cont = el.getParent();
      var mps = cont.getSize();
			var els = el.getSize();
			var scrollarea  = this.scrollarea;
			
			var setSize = function(hide){		
				var el = this.element;		
				var els = el.getSize();
				if(hide && !this.hidden){
					el.setStyles({
						'width' : els.x + 17
						+ el.getStyle('paddingLeft').toInt()
						+ el.getStyle('paddingRight').toInt()
					});
				}
				else if((!hide && this.hidden)) {
					
					el.setStyles({
						'width' : els.x - 17
						- el.getStyle('paddingLeft').toInt()
						- el.getStyle('paddingRight').toInt()
					});
				}
				this.hidden = hide;
			}.bind(this);
			
					
			scrollarea.setStyle('height', els.y-2);
			this.timeslider.update();
			scrollarea.getChildren('.scrCenter')[0].setStyle('height', scrollarea.getSize().y - 20);
			hand.getChildren('.hCenter')[0].setStyle('height', hand.getSize().y - 11);

			if(this.timeslider.hidden) {
				scrollarea.fade('hide');	
			}
			else {
				scrollarea.fade('show');
			}
			setSize(this.timeslider.hidden);
		
    }

});


var updateUserStatus = new Class({
	Implements: [Options,Events],
	options: {
		first : true,
		onLogin: {},
		onLogout: {},
		onFirst: {},
		onOther: {}
	},
	isLoggedin: false,
	fb: false,
	userData: [],
	preferences: {},
	initialize: function(options){
		this.setOptions(options);
		this.updateStatus.apply(this);
	},
	updateStatus: function(){
		new Request.JSON({
			url: '/api/userstatus.json',
			onSuccess: function(json, text){
				if(json){
					json = $H(json);
					this.userData = json;
					if(json.user_settings.preferences)
					{
						this.preferences = json.user_settings.preferences;
						$H(this.preferences).each(function(val, item){
							this.preferences[item] = val.toInt();
						}.bind(this));
						this.setPreferences(this.preferences);
						this.setStatistics();
					}
					else {
						this.preferences = {"show_caption": 1, "show_torrent": 1, "original_date": 1, "callView" : 0};
					}
					this.isLoggedin = (json.user_email) ? true : false;
					this.fb_auth();
					this.setMenu(json.user_email);
				}

			}.bind(this)
		},this).send();
	},
	setMenu:  function(loggedin){
		if(loggedin)
		{
			$('usr_anonymous').hide();

			var usrName = (this.fb) ? ('{last_name} {first_name}').substitute(this.fb) : this.userData.user_email;
			var usettingsbtn = $('usr_loggedin').getElement('a[trigger="usettings"]');
			usettingsbtn.set('html', usrName);
			$('usr_loggedin').show();
			this.fireEvent('login');			
		}
		else
		{
			$('usr_loggedin').hide();
			$('usr_anonymous').show();
			this.fireEvent('logout');
		}
		if(!this.options.first){
			this.fireEvent('other');
		}
		else {
			this.fireEvent('first');
			this.options.first = false;
		}
	},
	setPreferences: function(prefs){
		$H(prefs).each(function(val, item){
			var chb = document.getElement('input[type="checkbox"][name="user_settings[preferences][' + item + ']"]');
			if(!chb)
				return false;
			if(val.toInt())
				chb.set('checked', 'checked');
			else
				chb.set('checked', false);
				
			FancyForm.update(chb.getParent('label'));			
		});
	},
	setStatistics: function(){
		if(!$('statistics') || !'user_statistics' in this.userData)
			return false;
		var self = this;
		$$('#statistics dd[rel]').each(function(elem){
			if(elem.get('rel') in self.userData.user_statistics)
				elem.set('html', $H(self.userData.user_statistics).get(elem.get('rel')) + '&nbsp; db');
		});
	},
	logout: function(){

		if(this.fb)
			FB.logout(this.updateStatus.bind(this));

		new Request.JSON({
			url: '/api/userlogout.json',
			onSuccess: function(json, text){
				if(json){
					json = $H(json);
					this.userData = json;
					this.fb_auth();
					this.setMenu(json.user_email);
					this.isLoggedin = (json.user_email) ? true : false;
					this.preferences = {"show_caption": 1, "show_torrent": 1, "original_date": 1};
				}

			}.bind(this)
		},this).send();
		
	},
	fb_registerUser: function(){
		new Request.JSON({
			url: '/api/fb_register.json',
			onSuccess: function(json, text){			
				this.logout();
				this.updateStatus();
			}.bind(this)
		},this).send();	
	},
	fb_auth: function(){
		if(this.userData.user_settings && this.userData.user_settings.fb && this.userData.user_settings.fb.uid)
			this.fb = this.userData.user_settings.fb;
		else
			this.fb = false;
	},
	fb_Connect: function(){
		//this.fb_registerUser();
		settings.togglePanel();
		this.updateStatus();
	}
});

var userInteract = new Class({
	Implements: [Options, Events],
	Options: {
		pointyTipOptions: {
			point: 3
		},
		url: '',
		toggle: $empty(),
		submitOnChange: false,
		onSuccess: $empty()
	},
	form : $empty(),
	panel: $empty(),
	btn: $empty(),
	fvalidator: $empty(),
	initialize: function(panel, options)
	{
		var self = this;
		this.setOptions(options);
		this.panel = panel;
		if(!this.panel)
			return false;
		this.btn = document.getElement('a[trigger="' + this.panel.get('id') + '"]');
		if(!this.btn)
			return false;
		this.btn.addEvent('click', this.toggleEv.bind(this));	
		
		this.form = this.panel.getElement('form');	
		if(!this.form)
			return false;	
		
		this.keybevs = new Keyboard({
		    defaultEventType: 'keyup', 
		    events: { 
					'esc' : function(){
						if(this.panel.retrieve('status', false))
							this.togglePanel();
					}.bind(this)
		    }
		}).deactivate();
			
		this.fvalidator = new FormValidator.Tips(this.form,{
			evaluateFieldsOnBlur: false,
			evaluateFieldsOnChange: false,
			pointyTipOptions: this.options.pointyTipOptions
		});
		
		this.resetbtn = this.form.getElement('input[type="reset"]');
		if(this.resetbtn)
			this.resetbtn.addEvent('click', this.toggleEv.bind(self));
		var sendForm = function(e){
			try {	e.preventDefault();	}	catch(err){}
			
			if (!self.fvalidator.validate(e))
				    	return false;

	    new Request.JSON({
	        url: self.options.url,
	        method: 'post',
	        onSuccess: function(json) {
						if(json == 'OK'){
							userstatus.updateStatus.run(null, userstatus);
							if(!self.options.submitOnChange)
							{
								self.showInfo();						
								self.form.clearForm();
							}
						}
						else {
							self.showWarning();
						}

					}
	    }).send(self.form);
		};
		
		if(this.options.submitOnChange)
		{
			this.form.getElements('input[type="select"], input[type="text"], textarea,input[type="checkbox"], input[type="radio"]').addEvent('change', sendForm);
		}
		
		this.form.addEvent('submit', sendForm);
		
	},
	togglePanel: function(){
		if(this.options.toggle && !this.options.toggle())
			return false;
		var mv = new Fx.Tween(this.panel, {link: 'cancel', transition: 'sine:in'});
		var status = this.panel.retrieve('status',false);
		
		if(this.keybevs)
		if(status){	
			this.keybevs.deactivate();
			k.activate();
			deactivateElement();
			mv.start('top', -this.panel.getStyle('height').toInt());
		}
		else {
			this.keybevs.activate();
			mv.start('top', 0);
			try{this.panel.getElement('input[type="text"]').focus();}catch(e){}
		}		
		this.panel.store('status', !status);
	},
	toggleEv: function(e){
		e.preventDefault();
		this.togglePanel();
		if(this.form)
			this.form.clearForm();
		if(this.fvalidator)
			this.fvalidator.reset();
	},
	showInfo: function()
	{
		var infob = this.panel.getElement('.infoBubble');
		if(!infob)
		{
			this.togglePanel();
			return;
		}	
		var self = this;
		infob.fade('show');
		(function(){
			infob.fade('out');
			self.togglePanel();
		}).delay(2000);
	},
	showWarning: function(){
		var wbub = this.panel.getElement('.warningBubble');
		if(!wbub)
			return;
			
		wbub.fade('show');
		(function(){
			wbub.fade('out')
		}).delay(5000);
	}
});

var userBtns = function(){
	settings = new userInteract($('usettings'), {
		pointyTipOptions: {
			point: 12
		},
		toggle: function(){
			if(userstatus.fb){
				window.location = 'http://www.facebook.com/profile.php?id=' + userstatus.fb.uid;
				return false;
			}
			return true;
		},
		url: api + 'usersettings.json'
	});
	login = new userInteract($('login'), {
		pointyTipOptions: {
			point: 11
		},
		url: api + 'userlogin.json'
	});
	register = new userInteract($('registration'), {
		pointyTipOptions: {
			point: 11
		},
		url: api + 'userregister.json'
	});
	
	new userInteract($('preferences'), {
		submitOnChange: true,
		url: api + 'userpreferences.json'
	});
	
	new userInteract($('lostpwd'), {
		url: api + 'lostpwd.json'
	});
	
	$('btnLogout').addEvent('click', function(e){
		e.preventDefault();
		userstatus.logout.run(null,userstatus);
	});
	if($('btnFeedback'))
	$('btnFeedback').addEvent('click', function(e){
		e.preventDefault();
		new feedbackPage();
	});
	
	$('fbLoginBtn').addEvent('login',function(){
		login.togglePanel();
		userstatus.updateStatus();
	});
	
	$('fbRegisterBtn').addEvent('login',function(){
		register.togglePanel();
		userstatus.updateStatus();
	});
	var helpCont = new Fx.Tween($('helpCont'), {transition: 'quad:in:out'});
	var helpPanel = new Fx.Tween($('helpPanel'), {transition: 'quad:in:out'});
	
	helpPanel.set('marginLeft', -$('helpPanel').getStyle('width').toInt());
	
	var helpToggle = function(e, animations){
		try {e.preventDefault();}catch(e){}
		
		animations = (animations == $empty()) ? true : animations;
		
		if($('helpCont').getStyle('height').toInt() == 0)
		{
			$('infoBtn').addClass('active');
			if(animations)
			{
				helpCont.start('height', $('helpCont').getScrollSize().y);
				helpPanel.start('marginLeft', 0);
			}
			else
			{
				helpCont.set('height', $('helpCont').getScrollSize().y);
				helpPanel.set('marginLeft', 0);
			}
		}
		else {
			$('infoBtn').removeClass('active');
			if(animations)
			{
				helpCont.start('height', 0);
				helpPanel.start('marginLeft', -$('helpPanel').getStyle('width').toInt());
			}
			else 
			{
				helpCont.set('height', 0);
				helpPanel.set('marginLeft', -$('helpPanel').getStyle('width').toInt());
			}
			if(typeof window.history.replaceState == 'function')
				try{ window.history.replaceState(1, document.title, new URI().set('fragment', '')); }catch(e){}
			else
			{
				var uri = new URI().set('fragment', 'top');
				uri.go();
			}
		}		
	};
	
	$('infoBtn').addEvent('click', helpToggle);	
};

var feedbackPage = new Class({
	Extends: modalController,
	options: {
		customTitle: 'Mondd el mit gondolsz...',
		customClass: 'feedbackPage',
		customURI: 'feedback'
	},
	loadContent: function(){
		var self = this;
		new Element('h2', {'html' : 'Mondd el mit gondolsz...'}).inject(this.wrap);
		var feedbackForm = new Element('form', {'action' : api + 'sendFeedback.json'}).inject(this.wrap);
		new Element('textarea[rows=10][cols=70][name=content]').inject(new Element('label', {'html' : '&Iacute;rd meg p&aacute;r sorban mit gondolsz a &bdquo;Mit n&eacute;zel?&rdquo;-r&#x151;l...'}).inject(feedbackForm));
		var p = new Element('p').inject(feedbackForm);
		new Element('input[type=reset][value=Mégsem]')
		.inject(p)
		.addEvent('click', function(){
			self.dispose();
		});
				
		new Element('input[type=submit][value=Visszajelzés küldése]').inject(p);
		
		new Form.Request(feedbackForm, null, {
			resetForm: false,
			onSuccess: function(){
				new Element('div.green', {html : 'Az üzeneted megkaptam, köszönöm!'}).replaces(feedbackForm);
				(function(){
					this.dispose();
				}).delay(5000, self);
			},
			onFailure: function(){
				var msg = new Element('div.red', {'html' : 'Az üzenet elküldése nem sikerült, próbáld meg később.'}).inject(feedbackForm, 'before');
				(function(){
					new Fx.Tween(this, {link: 'chain'}).start('opacity', 1, 0).start('height', 0).chain(function(){this.dispose();}.bind(this));
				}).delay(5000, msg);
			}
		});				
	}
});

var sliderRadio = new Class({
	Implements: [Options, Events],
	options: {
		onChange: {},
		initialStep: 0,
		currentStep: 0
	},
	sliderKnob: {},
	container: {},
	steps: {},
	slider: {},
	initialize: function(container, options)
	{
		this.setOptions(options);
		this.container = container;
		this.sliderKnob = this.container.getElement('.slider');
		this.steps = this.container.getElements('label');
		this.options.currentStep = this.options.initialStep;
		if(!this.sliderKnob)
			return;
		var self = this;
		
		var updateknob = function(step){
			self.sliderKnob.getElement('span').set('class', self.steps[step-1].get('class'));
			self.steps[step-1].checked = 1;
		};
		
		this.slider = new Slider(this.container, this.sliderKnob, {
			steps: this.steps.length,
			range: [1, this.steps.length],
			initialStep: this.options.initialStep+1,
			onChange: updateknob,
			onComplete: function(step)
			{
				this.set(step);
				if(self.options.currentStep != (step-1))
				{
					self.options.currentStep = (step-1);
					self.fireEvent('change', self.steps[self.options.currentStep].getElement('input').get('value'));
				}
			}
		});	
		updateknob(this.options.initialStep+1);
	},
	dispose: function(){
		this.slider.detach();
	}
});

var parseLocation = function(){
	var dir;
	if(document.location.pathname.length > 1)
	{
		dir = document.location.pathname;
		if(typeof window.history.pushState != 'function')
		{
			new URI().set('directory', '').set('file', '').set('fragment', dir).go();
			window.stop();
			return;
		}
	}
	else if(new URI(document.location).get('fragment'))
		dir = new URI(document.location).get('fragment');
	else
		return {param : 0, value: 0};

	dir = (dir[0] == '/') ? dir.substr(1) : dir;
	dir = dir.split('/');
	if(!dir.length || dir.length > 2)
		return {param : 0, value: 0};
	else if(dir.length == 1)
		return {param : dir[0], value: 0};
		
	return {param : dir[0], value: dir[1]};
};

myKeyboard = Class.refactor(Keyboard, {
	addNew: function(elem){
		var t = elem.get('rel') ? elem.get('rel') : elem.get('text');
		k.addShortcut(t,{
			keys: elem.get('accesskey'),
			description: t,
			handler: this.evh.bind(elem)
		});
		elem.removeProperty('accesskey');			
	},
	evh: function(e){
		if(!['input', 'textarea'].contains($(e.target).get('tag')) && this.isVisible())
			e.preventDefault();
		else
			return true;
		e = new Event(e);
		switch(this.get('tag'))
		{
			case "a":
				this.fireEvent('click', e);
			break;

			case "input":
			case "textarea":
				if(this.get('type') == 'submit' && this.getParents('form').length)
					this.getParents('form').fireEvent('submit', e);
				else
					this.focus();
			break;
		}
		k.activate();
	}
});

var deactivateElement = function(){
	if('activeElement' in document && $(document.activeElement).get('tag') != 'body')$(document.activeElement).blur();
};

k = new myKeyboard({active:true});
window.addEvent('domready', function(){
	//userstatus = new updateUserStatus();

	title = document.getElement('title');
	document.getElement('title').store('title', title.get('html'));
	
	userBtns();
	
	var loc = parseLocation();

	var historyEvents = function(loc){

		if(loc && ('param' in loc))
		switch(loc.param)
		{
			case "s":
				if(typeof seriesPage == 'function')
					new seriesPage(loc.value);
			break;
			
			case "feedback":
				if(typeof feedbackPage == 'function')
					new feedbackPage();
			break;
			
			default:
				if(typeof openSubpage == 'object' && 'dispose' in openSubpage)
					openSubpage.dispose();				
			break;
		}
	};
	
	historyEvents(loc);

	window.onpopstate = function(event) {  
		currentState = event.state;
	  historyEvents(event.state);
	};
	if ("onhashchange" in window)
	window.onhashchange = function(event) {  
		if(typeof openSubpage == 'object' && openSubpage.hash == document.location.hash.substr(1))
			return false;
		var loc = parseLocation();
	  historyEvents(loc);
	};
	
	
	new Tips.Pointy($$('.tip'),
	 {
		pointyTipOptions: {
			zIndex: 99,
			point: 12,
			offset: {x: 0, y: -10},
			width: 'auto'
		},
		className: 'smallTip'
	});
	
	new Tips.Pointy($$('.tip2'),
	 {
		pointyTipOptions: {
			zIndex: 99,
			point: 11,
			offset: {x: 0, y: 0},
			width: 'auto'
		},
		className: 'smallTip'
	});
	
	window.onerror = function(){
		return false;
	};
	
	$$('img').addEvent('error',function() { 
	   this.dispose(); 
	});
	
	$$('a[href="#"]').each(function(elem){
		elem.removeProperty('href');
		elem.addEvents({
			'mouseenter': function(){
				window.status = this.get('text');
			},
			'mouseleave': function(){
				window.status = '';
			}
		});
	});
	
	if(!Browser.Engine.webkit)
	{
		$$('a', 'img').setProperty('draggable', false);
		$$('a', 'img').each(function(el){el.ondragstart = function(){return false;};})
	}
		
	if($$("[accesskey]").length)
	{
		Array.each($$("[accesskey]"), function(elem){k.addNew(elem);});
	}
	
	deactivateElement.delay(100);

				
	// $(document.body).addEvent('contextmenu', function(e){
	//  	e.preventDefault();
	// });
});